package com.summer.data.connection.session;

import com.summer.data.connection.Session;
import com.summer.data.connection.SessionFactory;
import com.summer.data.connection.source.DataSourceSessionFactory;
import com.summer.data.dialect.DatabaseProductID;
import com.summer.data.dialect.Dialect;
import com.summer.data.dialect.DialectCenter;
import com.summer.data.exception.SqlException;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * sql执行器
 *
 * @author ydfqy
 */

public abstract class AbstractSession implements Session {

    protected SessionFactory sessionFactory;

    private Dialect dialect;

    public AbstractSession(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public AbstractSession(DataSource dataSource) {
        this.sessionFactory = new DataSourceSessionFactory(dataSource);
    }

    @Override
    public Dialect getDialect() {
        if (dialect == null) {
            try {
                Connection connection = getConnection();
                DatabaseMetaData databaseMetaData = connection.getMetaData();
                String dbProdName = databaseMetaData.getDatabaseProductName();
                int majorVersion = databaseMetaData.getDatabaseMajorVersion();
                DatabaseProductID productID = new DatabaseProductID(dbProdName, majorVersion);
                dialect = DialectCenter.getDialect(productID);
            } catch (SQLException e) {
                throw new SqlException(e);
            } finally {
                close();
            }
        }
        return dialect;
    }

    private String catelog;

    @Override
    public String getCurrentCatalog() {
        if (catelog == null) {
            try {
                Connection connection = getConnection();
                catelog = connection.getCatalog();
            } catch (SQLException e) {
                throw new SqlException(e);
            } finally {
                close();
            }
        }
        return catelog;
    }

    private String schema;

    @Override
    public String getCurrentSchema() {
        if (schema == null) {
            try {
                Connection connection = getConnection();
                schema = connection.getSchema();
            } catch (SQLException e) {
                throw new SqlException(e);
            } finally {
                close();
            }
        }
        return schema;
    }

}
